package com.gzlz.budejie.view;

import java.net.URL;

import com.gzlz.budejie.utils.BitmapCacheUtils;
import com.gzlz.budejie.utils.NetCacheUtils;
import com.lidroid.xutils.BitmapUtils;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class ItemImageView extends ImageView {
	
	ItemImageView itemImageView;
	private BitmapUtils bitmapUtils;
	private BitmapCacheUtils bitmapCacheUtils;
	String url;
	int position;
	private Bitmap bitmap;
	public ItemImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		bitmapUtils = new BitmapUtils(context);
		bitmapUtils.configDefaultBitmapConfig(Config.ARGB_4444);
		bitmapCacheUtils = new BitmapCacheUtils(handler);
		initView();
	}
	private void initView() {
		bitmap = bitmapCacheUtils.getBitmapFromUrl(
				url, position);// 主线程：由内存和本地
		if (bitmap != null) {
			this.setImageBitmap(bitmap);
		}
		
		this.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
				ImageView imgView = getView();
				dialog.setView(imgView);
				dialog.show();
				
			}
		});

	}
	protected ImageView getView() {
		ImageView imgView = new ImageView(getContext());
		imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		imgView.setImageBitmap(bitmap);
		return imgView;
	}
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case NetCacheUtils.SUCCESS:// 图片加载成功
				System.out.println("图片加载成功");
				Bitmap bitmap = (Bitmap) msg.obj;
				int postion = msg.arg2;
				/**
				 * Tag保存在自己身上
				 */
				itemImageView=(ItemImageView) itemImageView.findViewWithTag(postion);
				itemImageView.setImageBitmap(bitmap);
				
				break; 
			case NetCacheUtils.FAIL:// 图片加载失败
				postion = msg.arg2;
				System.out.println("图片加载失败");
				break;

			default:
				break;
			}
		};
	};
	/**
	 * 传入url position
	 * @param url
	 * @param position
	 */
	public void setUrlPosition(String url,int position){
		this.url = url;
		this.position = position;
	}
	
	
}
